﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Transactions;
using System.Xml;
using System.Xml.Serialization;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Metadata.SPI;
using T.FAS.Runtime.Page.Dao;
using T.FAS.Runtime.Metadata.Entity.Page;

namespace T.FAS.Runtime.Page.Plugin
{
    /// <summary>
    /// 主题元数据管理
    /// </summary>
    public class ThemeRTPManager : AbsMetaDataManager, IMetaDataManager
    {
        public void Save(IMetaDataContent metaData)
        {

        }
        public void Delete(IMetaDataContent metaData)
        {

        }
        public void Update(IMetaDataContent metaData)
        {

        }
        public IMetaDataContent GetMetaDataContent(string metaDataId)
        {
            if (string.IsNullOrEmpty(metaDataId))
                throw new FasException(ThemeExceptionCode.InValidParam, "metaDataId参数为空");
            try
            {
                var themeMetaData = new ThemeMetaDataLogic().GetThemeMetaData(metaDataId);
                if (themeMetaData != null)
                {
                    themeMetaData.MetaDataID = themeMetaData.ID;
                    themeMetaData.MetaDataCode = themeMetaData.Code;
                    themeMetaData.MetaDataName = themeMetaData.Name;
                    return themeMetaData;
                }
            }
            catch (Exception e)
            {
                throw new FasException(ThemeExceptionCode.GetFailed, "获取主题元数据失败" + e.ToString());
            }
            return null;
        }
        public string SerializeObject(IMetaDataContent metadata, MetadataSerializeType serializeType)
        {
            if (metadata == null) return string.Empty;
            try
            {
                switch (serializeType)
                {
                    case MetadataSerializeType.XML:
                        var serializer = new XmlSerializer(typeof(ThemeMetaData));
                        using (var stringWriter = new StringWriter())
                        {
                            using (var writer = XmlWriter.Create(stringWriter))
                            {
                                serializer.Serialize(writer, metadata);
                                return stringWriter.ToString();
                            }
                        }

                    case MetadataSerializeType.JSON:
                    default:
                        return JsonConvert.SerializeObject(metadata);
                }
            }
            catch (Exception e)
            {
                throw new FasException(ThemeExceptionCode.SerializeFailed, "主题元数据序列化失败" + e.ToString());
            }
        }
        public IMetaDataContent DeserializeObject(string metaDataString, MetadataSerializeType serializeType)
        {
            if (string.IsNullOrWhiteSpace(metaDataString))
                return null;
            try
            {
                switch (serializeType)
                {
                    case MetadataSerializeType.XML:
                        var serializer = new XmlSerializer(typeof(ThemeMetaData));
                        using (var stream = new StringReader(metaDataString))
                        {
                            return serializer.Deserialize(stream) as ThemeMetaData;
                        }

                    case MetadataSerializeType.JSON:
                    default:
                        ThemeMetaData themeMetaData = JsonConvert.DeserializeObject<ThemeMetaData>(metaDataString);
                        themeMetaData.ID = themeMetaData.MetaDataID;
                        themeMetaData.Code = themeMetaData.MetaDataCode;
                        themeMetaData.Name = themeMetaData.MetaDataName;
                        return themeMetaData;
                }
            }
            catch (Exception e)
            {
                throw new FasException(ThemeExceptionCode.DeserializeFailed, "主题元数据反序列化失败" + e.ToString());
            }
        }

        public ValidateResult Validate(IMetaDataContent metaData)
        {
            return new ValidateResult();
        }

        public void Release(IMetaDataContent metaData, ReleaseStrategy releaseStrategy)
        {

        }

        public ConflictMessage ConflictCheck(List<IMetaDataContent> releasedMetaData, IMetaDataContent releaseingMetaData)
        {
            return new ConflictMessage();
        }

        public IList<MetaDataExportContent> Export(params IMetaDataContent[] metaDataList)
        {
            return new List<MetaDataExportContent>();
        }

        /// <summary>
        /// 元数据保存
        /// </summary>
        /// <param name="metaData"></param>
        public void Import(IList<MetaDataExportContent> contents, MetaDataImportStrategy importStrategy)
        {

            foreach (var exportContent in contents)
            {
                ThemeMetaData themeMetaData = null; 
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
                {
                    new ThemeMetaDataLogic().DeleteThemeMetaData(exportContent.MetaDataId);
                    if (importStrategy == MetaDataImportStrategy.Replace)
                    {
                        var metaData = this.DeserializeObject(exportContent.Content, MetadataSerializeType.JSON);
                        themeMetaData = (ThemeMetaData)metaData;
                        themeMetaData.ID = metaData.MetaDataID;
                        themeMetaData.Name = metaData.MetaDataName;
                        themeMetaData.Code = metaData.MetaDataCode;
                        new ThemeMetaDataLogic().AddThemeMetaData(themeMetaData);
                    }
                    scope.Complete();
                }
                if (themeMetaData != null)
                {
                    string fileName = FileTool.GetFileName(themeMetaData.MetaDataCode);
                    string json = $"{{Name:\"{fileName}\",Extension:\"css\",PathId:\"141\",CustomFileName:\"{fileName}\"}}";
                    FileTool.UploadFile(fileName, json, themeMetaData.StyleContent);
                }
            }
        }
        public void Enable(params IMetaDataContent[] metaData)
        {

        }

        public MetaDataCompileResult Compile(IList<IMetaDataContent> metadatas)
        {
            return new MetaDataCompileResult();
        }
        public List<MetaDataDependency> GetMetaDataDependencys(IMetaDataContent metaDataContent)
        {
            return new List<MetaDataDependency>();
        }

        public MetaDataUpdateSet GetMetaDataUpdateSet(IMetaDataContent oldMetaData, IMetaDataContent newMetaData)
        {
            MetaDataUpdateSet updateSet = new MetaDataUpdateSet();
            updateSet.UpdateItemList = new List<MetaDataUpdateItem>();
            if (oldMetaData.MetaDataName != newMetaData.MetaDataName)
            {
                MetaDataUpdateItem updateItem = new MetaDataUpdateItem();
                updateItem.UpdateType = MetaUpdateType.Item_Theme_Name;
                updateItem.UpdateKey = "Name";
                updateItem.NewValue = newMetaData.MetaDataName;
                updateItem.OldValue = oldMetaData.MetaDataName;
                updateSet.UpdateItemList.Add(updateItem);
            }
            return updateSet;
        }
        public MetaUpdateResult UpdateDependencyMetaData(IMetaDataContent metaDataContent, MetaDataUpdateSet updateSet)
        {
            return null;
        }
        public IRefSchemaEntity BuildRefSchema(IMetaDataContent metaDataContent)
        {
            return null;
        }
        public IEnumerable<Metadata.Entity.Term> BuildTerms(IMetaDataContent metaDataContent, IEnumerable<Metadata.Entity.Term> terms = null)
        {
            return new List<Metadata.Entity.Term>();
        }
        public IRefSchemaEntity DeserializeRefSchemaEntity(string schemaEntityJson)
        {
            return null;
        }
        ValidateResult IMetaDataManager.CompatibleValidate(IMetaDataContent metaData, IMetaDataContent oldMetaData)
        {
            return new ValidateResult { state = "1" };
        }

        public override MetaGenerateCodeResult GenerateCode(IMetaDataContent metadata, bool isInternational)
        {
            throw new NotImplementedException();
        }
    }
}
